var jv = require("libjv").default;
var http = require('http');
const fs = require("fs");
const line_break = "\r\n";

jv.getEncoding = function (contentType) {
    if (!contentType) return "";
    var charsetIndex = contentType.indexOf("charset=");
    if (charsetIndex < 0) {
        return "";
    }
    return contentType.slice(charsetIndex + 8).trim();
};



Object.defineProperty(http.IncomingMessage.prototype, "logToFile", {
    value(logFile,eachLog) {
        var msg = Array.from(this.msgs).join(line_break);
        console.log(msg);

        if (logFile) {
            var fileName = logFile;
            if (eachLog) {
                var li = logFile.lastIndexOf(".");
                fileName = fileName.slice(0, li) + "-" + Date.now().toDateString("yyyyMMddHHmmssfff") + fileName.slice(li);
            }

            if( !this.logFilePromise ){
                this.logFilePromise = Promise.resolve();
            }
            this.logFilePromise.then(()=>{
                fs.appendFile(fileName, msg + line_break, 'utf8',error=>{
                    if (error) return console.log("追加文件失败: " + error.message);
                });
            });
        }
    }, enumerable: false
});
